
import 'dart:ffi'; // For FFI
import 'dart:io'; // For Platform.isX
import 'dart:math';
import 'dart:typed_data';

import 'package:ffi/ffi.dart';
import 'package:flutter/cupertino.dart';
import 'package:wch_plugin/wch_plugin_platform_interface.dart';

class WchPlugin {
  static String platformVersion = '1.0';
  //函数声明
  late final Pointer<Int32> Function(Pointer<Utf8>, int) readEdf;
  late final int Function(int, int) filterFunc;
  late final int Function() releaseFunc;
  late final int Function(Pointer<Utf8>) totalPageFunc;

  Future<String?> getPlatformVersion() {
    return WchPluginPlatform.instance.getPlatformVersion();
  }

  //初始化
  WchPlugin(){
    final DynamicLibrary myNativeLib = Platform.isAndroid
        ? DynamicLibrary.open('libwch_plugin.so')
        : DynamicLibrary.process();
    //静态链接中的符号可以使用 DynamicLibrary.executable
    //或 DynamicLibrary.process 来加载。
    //动态链接库在 Dart 中可以通过 DynamicLibrary.open 加载。

    //函数定义
    releaseFunc = myNativeLib.lookup<NativeFunction<Int32 Function()>>('flutterRelease').asFunction();
    readEdf = myNativeLib.lookup<NativeFunction<Pointer<Int32> Function(Pointer<Utf8>, Int32)>>('flutterread_physical_samples').asFunction();
    filterFunc = myNativeLib.lookup<NativeFunction<Int32 Function(Int32, Int32)>>('flutterFilter').asFunction();
    totalPageFunc = myNativeLib.lookup<NativeFunction<Int32 Function(Pointer<Utf8>)>>('getEdfPage').asFunction();

  }

  //给外部app调用的 对象方法
  List<int> readEdfData(String filePath, int page){
    ///第3个参数为实际长度，调用函数后会被赋值
    Pointer<Int32> buf = readEdf(filePath.toNativeUtf8(), page);
    Int32List bytes = buf.asTypedList(750);

    return bytes;
  }

  int filterDataFunc(int origin, int type){
    int filterVal = filterFunc(type, origin);
    return filterVal;
  }

  int getTotalPage(String filePath){
    int page = totalPageFunc(filePath.toNativeUtf8());
    return page;
  }

  void releaseFilter() {
    releaseFunc();
  }

  //给外部app调用的 静态方法
  static String getVersion(){
    return platformVersion;
  }

}